// import块
const fs = require('fs');
const request = require('request');

// 参数定义块
// 日志文件请求接口
const requestUrl = "http://zwylog.szjs.gov.cn/internal/search/ese";
// 日志被保存的时使用的文件名
const fileName = "jscj.log";
// 查询开始时间
const beginTime = new Date("2021/03/04 00:00:00");
// 查询结束时间
const endTime = new Date("2021/03/04 10:50:03");
const pageSize = 10000;
// 主机名称
const hostName = "ggzf-hc";
// 主机名称
// 系统中日志文件路径
const source = "/home/weblogic/log/jscj.log"


var queryConfig = {
    "params": {
        "index": "applog*",
        "body": {
            "version": true,
            "size": pageSize,
            "sort": [{"@timestamp": {"order": "asc", "unmapped_type": "boolean"}}],
            "aggs": {
                "2": {
                    "date_histogram": {
                        "field": "@timestamp",
                        "fixed_interval": "30s",
                        "time_zone": "Asia/Shanghai",
                        "min_doc_count": 1
                    }
                }
            },
            "stored_fields": ["*"],
            "script_fields": {},
            "docvalue_fields": [{"field": "@timestamp", "format": "date_time"}],
            "_source": {"excludes": []},
            "query": {
                "bool": {
                    "must": [],
                    "filter": [{"match_all": {}}, {"match_phrase": {"host.name": hostName}}, {"match_phrase": {"log.file.path": source}}, {
                        "range": {
                            "@timestamp": {
                                "gte": beginTime.toISOString(),
                                "lte": endTime.toISOString(),
                                "format": "strict_date_optional_time"
                            }
                        }
                    }],
                    "should": [],
                    "must_not": []
                }
            },
            "highlight": {
                "pre_tags": ["@kibana-highlighted-field@"],
                "post_tags": ["@/kibana-highlighted-field@"],
                "fields": {"*": {}},
                "fragment_size": 2147483647
            }
        },
        "preference": 1614831589677
    }
}

const parseLog = function (jsonBody) {
    let log = "";
    const hits = jsonBody && jsonBody.rawResponse && jsonBody.rawResponse.hits && jsonBody.rawResponse.hits.hits;
    if (hits instanceof Array) {
        for (var i = 0; i < hits.length; i++) {
            var item = hits[i];
            log += ("\n" + item._source.message);
        }
    }
    fs.writeFile(fileName, log, {flag: 'w', encoding: 'utf-8', mode: '0666'}, function (error) {
        if (error) {
            console.log("文件写入失败")
            console.log(error);
        } else {
            console.log("文件写入成功");
        }
    });
}

// 组装查询
const requestData = JSON.stringify(queryConfig) + "\n";

const requestConfig = {
    url: requestUrl,
    method: "POST",
    headers: {
        "content-type": "application/json",
        "kbn-version": "7.10.2"
    },
    body: requestData
}
const handleResp = function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var jsonBody = JSON.parse(body);
        var isRunning = jsonBody.isRunning;
        var indexId = jsonBody.id;
        var retryTimes = 1;
        if (false == isRunning) {
            parseLog(jsonBody);
        } else {
            const retry = function () {
                console.log("第" + (retryTimes++) + "次查询数据。")
                requestConfig.url = requestUrl + "/" + indexId;
                request(requestConfig, handleResp);
            };
            setTimeout(retry, 1000);
        }
    }
};
// 数据请求块
request(requestConfig, handleResp);
